// pages/person/personInfo.js
const httpUtils = require('../../utils/httpUtils')
const ui = require('../../utils/ui')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    userPhone: '',
    headerUrl: "/images/person/defaultHeader.png"
  },

  onLoad(options) {
    this.setData({
      userName: wx.getStorageSync('USERDATA').userName,
      userPhone: wx.getStorageSync('USERDATA').mobile,
      headerUrl: wx.getStorageSync('USERDATA').avatar
    })
  },
  onShow() {
    this.requestUserInfo();
  },
  //头像加载错误处理
  headerImageLoadFail() {
    this.setData({
      headerUrl: "/images/person/defaultHeader.png"
    })
  },
  onChooseAvatar(e) {
    this.setData({
      headerUrl: e.detail.avatarUrl
    });
    wx.uploadFile({
      url: 'https://shangjinxia.ltd/api/image/file',
      filePath: e.detail.avatarUrl,
      name: 'file',
      formData: {},
      success(res) {
        // 上传完成需要更新 upload_files
        var result = JSON.parse(res.data);
        let obj2 = {
          method: 'PUT',
          url: '/user/'+wx.getStorageSync('USERDATA').platformId,
          data: {
            avatar: result.uploadFileUrl
          }
        }
        httpUtils.request(obj2).then(res => {
          ui.showToast('修改成功');
        }).catch(err => {
          console.log('ERROR')
        });
      },
      fail() {
        ui.showToast('上传失败');
      }
    });
},
//请求个人信息
requestUserInfo() {
  let obj = {
    method: 'GET',
    url: '/user/' + wx.getStorageSync('USERDATA').platformId
  }
  httpUtils.request(obj).then(res => {
    this.setData({
      headerUrl: res.data.avatar,
      userName: res.data.nickName,
      userPhone: res.data.mobile,
    })
  }).catch(err => {
    console.log('ERROR')
  });
},
})